<template>
  <div class="app-container flex-col" v-loading="pageLoading">
    <div class="p-20">
      <el-row :gutter="30">
        <el-col :span="12">
          <line-group :functionName="functionName" :data="initData" @onClear="onClearGroupOrEmp"
            @onChange="checkLineGroup"></line-group>
        </el-col>
        <el-col :span="12">
          <emp-scan :data="initData" :focus.sync="empFocus" @onClear="onClearGroupOrEmp" @onChange="afterScanEmp">
          </emp-scan>
        </el-col>
      </el-row>
    </div>
    <div class="p-20 z-border-t">
      <el-row :gutter="30">
        <el-col :span="8">
          <div class="flex flex-center">
            <label class="mr-15">包装层级</label>
            <el-select v-model="initData.package_code" class="mr-15 flex1" :disabled="!canSelectPackLevel"
              @change="afterPackLevelChange" placeholder="请选择包装层级">
              <el-option v-for="item in packageOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button type="info" round @click="clearPackageCode">变更</el-button>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="flex flex-center">
            <span class="mr-20">请扫描条码</span>
            <el-input class="flex1 z-scan" v-model="scanData" ref="scan" @keyup.enter.native="afterScan" size="large"
              :disabled="!canScan"></el-input>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="flex1 flex z-border-t" style="overflow-x: hidden; overflow-y: auto;">
      <div class="p-20 z-panel z-border-r" style="width: 30%;">
        <div class="z-panel-title">产品包装规范</div>
        <div class="z-panel-body">
          <el-row style="margin-top:15px">
            <el-col :span="6" class="col-left">工单号: </el-col>
            <el-col class="col-right" :span="18">{{mo.mo_no}}</el-col>
          </el-row>
          <el-row>
            <el-col class="col-left" :span="6">客户: </el-col>
            <el-col class="col-right" :span="18">{{mo.cust_name}}</el-col>
          </el-row>
          <el-row>
            <el-col class="col-left" :span="6">产品名称: </el-col>
            <el-col class="col-right" :span="18">{{mo.material_name}}</el-col>
          </el-row>
          <el-row>
            <el-col class="col-left" :span="6">产品编码: </el-col>
            <el-col class="col-right" :span="18">{{mo.material_code}}</el-col>
          </el-row>
          <el-row>
            <el-col class="col-left" :span="6">包装量: </el-col>
            <el-col class="col-right" :span="18">{{mo.size}}</el-col>
          </el-row>
        </div>
      </div>
      <div class="z-panel p-20 flex1">
        <div class="z-panel-title">待包装序号列表</div>
        <div style="margin-bottom:10px">
          <span>产品总数: </span><span>{{productCnt}}</span> <span style="margin-left:50px">序号总数:
          </span><span>{{initData.snList.length}}</span>
        </div>
        <div class="z-panel-body">
          <el-table :data="initData.snList" border style="width: 100%">
            <el-table-column prop="scan_sn" label="序号"> </el-table-column>
            <el-table-column prop="batch_qty" label="产品数量"> </el-table-column>
            <!-- <el-table-column prop="remain" label="剩余"> </el-table-column> -->
          </el-table>
        </div>
      </div>
      <div class="p-20 z-panel z-border-l" style="width: 30%;">
        <div class="z-panel-title">已生成的包装序号列表</div>
        <div class="z-panel-body" style="margin-top:10px">
          <!-- <el-table :data="barcodeList" border style="width: 100%">
                        <el-table-column prop="time" label="生成日期"> </el-table-column>
                        <el-table-column prop="code" label="序号"> </el-table-column>
                    </el-table> -->
          <div v-for="(item, index) in barcodeList" :key="index" style="margin:5px 0 5px 20px">
            <span>{{index+1}}. </span><span>{{item.time}}</span> <span
              style="margin-left:5px;color:#67C23A">{{item.code}}</span>
          </div>
        </div>
      </div>
    </div>
    <message-box :msgs="msgs"></message-box>
  </div>
</template>

<script>
import lineGroup from '@/components/WinClient/lineGroup'
import empScan from '@/components/WinClient/empScan'
import messageBox from '@/components/WinClient/messageBox'
import mixinClient from '@/views/_common/mixinClient'
import _ from 'lodash'
import dayjs from 'dayjs'
export default {
  name: 'packSnOrSsn',
  mixins: [mixinClient],
  components: { lineGroup, empScan, messageBox },
  data() {
    return {
      pageLoading: false,
      groupOptions: [],
      packageOptions: [],
      initData: {
        line: '',
        group: '',
        package_code: '',
        emp: '',
        empName: '',
        snList: [],
      },

      empFocus: false,
      scanData: '',
      msgs: [],
      snHistory: [],
      scanTimes: 0, //扫描次数
      sizeTotal: 0,
      checkObj: { mo_id: '', package_level: '' }, //检查flag
      mo: {},
      cntTotal: 0,
      bindDetailList: [],
      bindPass: false,
      barcodeList: [],
    }
  },
  created() {
    console.log(window.electron)
    // window.electron.getIpcRender.on('error-message', (event, arg) => {
    //     console.log(arg)
    //     console.log(window)
    // })

    var _tmp = localStorage.getItem(`${this.functionName}-initData`)
    if (_tmp) {
      let tmpObj = JSON.parse(_tmp)
      this.initData.package_code = tmpObj.package_code
    }
    this.getPackageLevel()
  },
  methods: {
    clearPackageCode() {
      this.initData.package_code = null
      this.checkLineGroup()
    },
    afterPackLevelChange() {
      localStorage.setItem(
        `${this.functionName}-initData`,
        JSON.stringify({
          line: this.initData.line,
          group: this.initData.group,
          package_code: this.initData.package_code,
        }),
      )
      this.checkLineGroup()
    },
    getPackageLevel() {
      this.$request(this.$api.dictionary + 'getdirectchildren', {
        parentType: 'package_level_name',
      }).then((r) => {
        this.packageOptions = r
      })
    },
    checkLineGroup() {
      if (!this.initData.line) return this.showMessage('请选择线别')
      if (!this.initData.group) return this.showMessage('请选择工站')
      if (!this.initData.package_code) return this.showMessage('请选择包装层级')
      this.checkEmp()
    },
    checkEmp() {
      if (!this.initData.empName) {
        this.showMessage('请扫描作业员')
        this.empFocus = true
        return
      } else {
        this.afterScanEmp(true)
      }
    },
    afterScanEmp(r) {
      if (r) {
        this.showMessage('请扫描序号', false)
        setTimeout(() => {
          this.$refs.scan.focus()
        }, 200)
      } else {
        this.showMessage('作业员不正确', true)
      }
    },
    afterScan() {
      this.scanData = this.scanData.trim()
      if (!this.scanData) {
        this.showMessage('没有扫描到任何内容', true)
        return
      }
      this.scanData = this.scanData.toUpperCase()
      if (this.scanData.toUpperCase() == 'UNDO') {
        this.undo()
        return
      }
      if (
        _.findIndex(this.initData.snList, (i) => {
          return i.scan_sn == this.scanData || i.shipping_sn == this.scanData || i.sn == this.scanData
        }) > -1
      ) {
        this.showMessage(`${this.scanData}序号已经存在,请确认。`, true)
        setTimeout(() => {
          this.$refs.scan.select()
        }, 200)
        return
      }
      if (this.scanData.toUpperCase() == 'END') {
        this.passStation()
        return
      }
      this.pageLoading = true

      this.$request(
        this.$api.mesPackage + 'checkpass',
        { ...this.initData, snList: [{ scan_sn: this.scanData, cnt: 0 }] },
        'post',
        true,
      )
        .then((r) => {
          this.pageLoading = false
          if (r) {
            let wip = r.routeRes.wips[0]
            let wips = r.routeRes.wips

            if (!this.checkObj.mo_id || !this.checkObj.package_level) {
              this.checkObj = {
                mo_id: r.mo.id,
                package_level: wip.package_level,
              }
            }
            if (r.mo.id != this.checkObj.mo_id)
              throw new Error('包装项必须是相同的工单，请检查' + this.scanData + '序号对应的工单号。')
            if (wip.package_level != this.checkObj.package_level)
              throw new Error('包装项当前包装层级必须相同,请检查' + this.scanData + '序号对应的当前包装层级。')

            //拼板只允许一条包装序号  bindpass 为true 表示是拼板
            if (wips.length > 1) {
              this.bindPass = true
            }
            this.cntTotal += r.remain
            // 拼板重复性检查，产品数量检查
            if (this.bindPass) {
              if (
                _.findIndex(this.bindDetailList, (v) => {
                  return v.scan_sn == this.scanData || v.shipping_sn == this.scanData || v.sn == this.scanData
                }) > -1
              ) {
                this.cntTotal -= r.remain
                throw new Error(this.scanData + '序号已在拼板中，请确认。')
              }

              if (this.cntTotal > r.pack.size) {
                this.cntTotal -= r.remain
                throw new Error('拼板包装数量不能大于包装量，请确认。')
              }
            }

            this.mo = r.mo
            this.mo.size = r.pack.size
            //单体,拼板,包装序号 --- package_level 0 产品序号，大于0是包装序号,sn_batch_qty =1 是单体
            let obj = {
              scan_sn: this.scanData,
              wip_id: wip.wip_id,
              sn: wip.serial_number,
              shipping_sn: wip.shipping_sn,
              cnt: r.remain, //需要包装的数量
              batch_qty: wip.wip_batch_qty, //产品数量
              remain: 0,
            }
            if (wip.package_level > 0 || wip.sn_batch_qty <= 1) {
              let snIndex = _.findIndex(wips, (v) => {
                return v.serial_number == this.scanData || v.shipping_sn == this.scanData
              })
              this.initData.snList.push({
                ...obj,
                sn: wips[snIndex].serial_number,
                shipping_sn: wips[snIndex].shipping_sn,
                batch_qty: wips.length > 1 ? r.remain : wip.wip_batch_qty,
              })
              //拼板处理
              if (wips.length > 1) {
                wips.forEach((v) => {
                  this.bindDetailList.push({
                    ...obj,
                    wip_id: v.wip_id,
                    sn: v.serial_number,
                    shipping_sn: v.shipping_sn,
                    bind_status: v.bind_status,
                    cnt: v.wip_batch_qty,
                    batch_qty: v.wip_batch_qty,
                  })
                })
              } else {
                this.bindDetailList.push(obj)
              }
            } else {
              // 批量产品
              //剩余包装数量
              let remain = _.sumBy(this.initData.snList, function (v) {
                return v.remain
              })
              //已有的包装数量
              let cntTmp = _.sumBy(this.initData.snList, function (v) {
                return v.cnt
              })
              let cntSum = r.remain + remain + cntTmp
              if (cntSum >= r.pack.size) {
                //其它sn remian 置为0
                this.initData.snList.forEach((v) => {
                  v.remain = 0
                })
                //把剩余的数量放到当前条码上
                let cntMo = cntSum % r.pack.size
                this.initData.snList.push({
                  ...obj,
                  cnt: cntSum - cntMo - remain - cntTmp,
                  remain: cntMo,
                })
              } else {
                this.initData.snList.push(obj)
                this.showMessage('请继续扫描序号或刷END打印标签。', false)
                return
              }
            }
            // 统一提交
            if (this.cntTotal >= r.pack.size) {
              console.log(this.initData.snList)
              let cntTotal = _.sumBy(this.initData.snList, function (o) {
                return o.cnt
              })
              if (cntTotal % r.pack.size != 0) throw new Error('数据异常，请刷UNDO重新扫描或联系管理员检查。')
              this.passStation()
            } else {
              setTimeout(() => {
                this.$refs.scan.select()
              }, 200)
              this.showMessage('请继续扫描序号或刷END打印标签。', false)
            }
          } else {
            setTimeout(() => {
              this.$refs.scan.select()
            }, 200)
          }
        })
        .catch((e) => {
          this.pageLoading = false
          if (this.initData.snList.length <= 0) {
            this.checkObj = {}
            this.cntTotal = 0
          }

          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
        })
    },
    passStation() {
      if (this.initData.snList.length <= 0) {
        this.showMessage('序号为空，请先扫描产品序号。', true)
        return
      }
      this.pageLoading = true
      let data = _.cloneDeep(this.initData)
      if (this.bindPass) {
        data.snList = this.bindDetailList
      }

      this.$request(this.$api.mesPackage + 'packsnorssn', data, 'POST', true)
        .then((r) => {
          let time = dayjs().format('YYYY-MM-DD HH:mm:ss')
          if (r.barcodeList.length <= 0) throw new Error('未生成包装序号。')
          r.barcodeList.forEach((v) => {
            this.barcodeList.unshift({ time, code: v })
          })
          //打印
          if (window.electron) {
            this.afterPassStation('包装成功，正在打印。')
            window.electron
              .print({
                fileUrl: this.$api.baseUrl + r.labelData.temp_url,
                fileName: '',
                content: r.labelData.data_content,
                directory: this.functionName,
              })
              .then((r) => {
                this.pageLoading = false
                this.showMessage('打印成功。请继续扫描下一产品。', false)
              })
              .catch((e) => {
                this.pageLoading = false
                this.showMessage('打印失败: ' + e, true)
              })
          } else {
            this.afterPassStation('包装成功,请继续扫描下一产品。')
          }
        })
        .catch((e) => {
          this.pageLoading = false
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
          this.scanTimes -= 1
        })
    },
    onClearGroupOrEmp() {
      this.clearScanData()
      this.initData.package_code = null
      this.checkLineGroup()
    },
    undo() {
      this.clearScanData()
      this.showMessage('重置OK，请重新扫描', false)
    },
    clearScanData() {
      this.scanData = ''
      this.initData.snList = []
      this.mo = {}
      this.scanTimes = 0
      this.checkObj = { mo_id: '', cust_id: '', package_level: '' }
      this.bindDetailList = []
      this.cntTotal = 0
      this.bindPass = false
    },

    submitClearData() {
      this.scanData = ''
      this.cntTotal = 0
      this.initData.snList = this.initData.snList.filter((v) => {
        return v.remain != 0
      })
      this.bindPass = false
      this.bindDetailList = []
      this.cntTotal = 0
      this.initData.snList.forEach((v) => {
        if (v.remain) {
          v.batch_qty = v.remain
          v.cnt = v.remain
          v.remain = 0
          this.cntTotal += v.cnt
        }
      })
      if (this.initData.snList.length <= 0) {
        this.checkObj = { mo_id: '', package_level: '' }
        this.mo = {}
      }
    },
    afterPassStation(msg) {
      this.showMessage(msg, false)
      this.submitClearData()
      setTimeout(() => {
        this.$refs.scan.focus()
      }, 200)
    },

    getLabelData(model) {
      this.pageLoading = true
      this.$request(this.$api.barcodeRule + 'mat/labelconfig/getLabelData', model, 'POST', true)
        .then((r) => {
          this.pageLoading = false
        })
        .catch((e) => {
          this.pageLoading = false
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
          this.scanTimes -= 1
        })
    },
  },
  computed: {
    productCnt: function () {
      return _.sumBy(this.initData.snList, function (o) {
        return o.batch_qty
      })
    },
    canScan: function () {
      return this.initData.line && this.initData.group && this.initData.empName
    },
    canSelectPackLevel: function () {
      return !this.initData.package_code
    },
    canInputEmp: function () {
      return !this.initData.empName && this.initData.line && this.initData.group
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/client.scss';
.z-panel-body .col-left {
  text-align: right;
  margin-bottom: 25px;
}
.z-panel-body .col-right {
  text-align: left;
  padding-left: 20px;
}
</style>
